﻿using System;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace MDigman.Camera.Media.Copier.WPF
{
    /// <summary>
    /// Simple class to get the make and model of the camera that took the picture and the date it was taken.
    /// </summary>
    class ExifPropertyReader
    {
        private string make = string.Empty;
        private string model = string.Empty;
        private DateTime date;

        public ExifPropertyReader(FileInfo file)
        {
            Image image = Image.FromStream(file.OpenRead(), true, false);
            if (image != null)
            {
                setProperties(image.PropertyItems);
            }
        }

        /// <summary>
        /// Make of camera that took picture.
        /// </summary>
        public string Make
        {
            get { return make; }
        }

        /// <summary>
        /// Model of camera that took picture.
        /// </summary>
        public string Model
        {
            get { return model; }
        }

        /// <summary>
        /// Date picture was taken.
        /// </summary>
        public DateTime Date
        {
            get { return date; }
        }

        private void setProperties(PropertyItem[] Properties)
        {
            foreach (PropertyItem item in Properties)
            {
                switch (item.Id)
                {
                    case 0x10F:
                        //Equip Make
                        make = getValue(item);
                        break;
                    case 0x110:
                        //Equip Model
                        model = getValue(item);
                        break;
                    case 0x132:
                        //Date Time
                        string dt = getValue(item);
                        int year = Convert.ToInt32(dt.Substring(0,4));
                        int month = Convert.ToInt32(dt.Substring(5,2));
                        int day = Convert.ToInt32(dt.Substring(8,2));
                        date = new DateTime(year, month, day);
                        break;
                }
            }
        }

        private string getValue(PropertyItem p)
        {
            string data = string.Empty;
            if (p.Type == 0x2)
			{
                // ASCII An 8-bit byte containing one 7-bit ASCII code.
                // The final byte is terminated with NULL, so remove it.
                data = Encoding.ASCII.GetString(p.Value).TrimEnd('\0');
			}
            return data;
        }
    }
}